package com.ruoyi.web.controller.customer;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.RestaurantBalanceDetail;
import com.ruoyi.common.core.domain.entity.RestaurantCustomer;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.RestaurantCustomerService;
import com.ruoyi.system.service.req.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Author: ruohao
 * @Date: 2023/8/23
 **/
@Api("用户信息")
@RestController
@RequestMapping("/shop/customer")
public class CustomerAccountController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CustomerAccountController.class);

    @Resource
    private RestaurantCustomerService restaurantCustomerService;

    @Validated
    @GetMapping("/listNormal")
    public TableDataInfo listNormal(@Valid CustomerQueryDTO customerQueryDTO) {
        startPage();
        List<RestaurantCustomer> list = restaurantCustomerService.getNormalCustomer(customerQueryDTO);
        return getDataTable(list);
    }

    @Validated
    @GetMapping("/listInner")
    public TableDataInfo listInner(@Valid CustomerQueryDTO customerQueryDTO) {
        startPage();
        List<RestaurantCustomer> list = restaurantCustomerService.getInnerCustomer(customerQueryDTO);
        return getDataTable(list);
    }

    @ApiOperation("获取用户信息")
    @Validated
    @GetMapping("/get")
    public AjaxResult get() {
        RestaurantCustomer query = new RestaurantCustomer();
        query.setCustomerId(String.valueOf(SecurityUtils.getUserId()));
        List<RestaurantCustomer> list = restaurantCustomerService.getCustomer(query);
        if (CollectionUtils.isEmpty(list)) {
            return success();
        }
        return success(list.get(0));
    }

    @GetMapping(value = "/normal/{id}")
    public AjaxResult getNormalInfo(@PathVariable Long id) {
        RestaurantCustomer restaurantCustomer = restaurantCustomerService.getNormalCustomerById(id);
        if (restaurantCustomer == null) {
            return error();
        }
        return success(restaurantCustomer);
    }

    @GetMapping(value = "/inner/{id}")
    public AjaxResult getInnerInfo(@PathVariable Long id) {
        RestaurantCustomer restaurantCustomer = restaurantCustomerService.getInnerCustomerById(id);
        if (restaurantCustomer == null) {
            return error();
        }
        return success(restaurantCustomer);
    }

    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addInner")
    public AjaxResult addInner(@Validated @RequestBody InnerCustomerAddDTO innerCustomerAddDTO) {
        checkInnerAddParam(innerCustomerAddDTO);
        Boolean result = restaurantCustomerService.createInnerCustomer(innerCustomerAddDTO, SecurityUtils.getLoginUser().getUser());
        if (result) {
            return success();
        }
        log.warn("新增客户 内部员工账户 失败");
        return error();
    }

    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addNormal")
    public AjaxResult addNormal(@Validated @RequestBody NormalCustomerAddDTO normalCustomerAddDTO) {
        checkNormalAddParam(normalCustomerAddDTO);
        Boolean result = restaurantCustomerService.createNormalCustomer(normalCustomerAddDTO, SecurityUtils.getLoginUser().getUser());
        if (result) {
            return success();
        }
        log.warn("新增客户 普通客户账户 失败");
        return error();
    }

    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateNormalBalance")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateNormalBalance(@Validated @RequestBody NormalUpdateBalanceDTO normalUpdateBalanceDTO) {
        RestaurantBalanceDetail restaurantBalanceDetail = restaurantCustomerService.changeCustomerBalance(normalUpdateBalanceDTO.getId(),
                normalUpdateBalanceDTO.getAmount(),
                normalUpdateBalanceDTO.getReason(),
                normalUpdateBalanceDTO.getType(),
                SecurityUtils.getLoginUser().getUser());
        return success(restaurantBalanceDetail.getId());
    }

    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateInnerBalance")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateInnerBalance(@Validated @RequestBody NormalUpdateBalanceDTO normalUpdateBalanceDTO) {
        RestaurantBalanceDetail restaurantBalanceDetail = restaurantCustomerService.changeCustomerBalance(normalUpdateBalanceDTO.getId(),
                normalUpdateBalanceDTO.getAmount(),
                normalUpdateBalanceDTO.getReason(),
                normalUpdateBalanceDTO.getType(),
                SecurityUtils.getLoginUser().getUser());
        return success(restaurantBalanceDetail.getId());
    }

    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateNormalCustomer")
    public AjaxResult updateNormalCustomer(@Validated @RequestBody UpdateCustomerDTO updateCustomerDTO) {
        try {
            restaurantCustomerService.updateCustomer(updateCustomerDTO, SecurityUtils.getLoginUser().getUser());
        } catch (Exception e) {
            log.warn("编辑客户失败", e);
            return error(e.getMessage());
        }
        return success();
    }

    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateInnerCustomer")
    public AjaxResult updateInnerCustomer(@Validated @RequestBody UpdateCustomerDTO updateCustomerDTO) {
        try {
            restaurantCustomerService.updateCustomer(updateCustomerDTO, SecurityUtils.getLoginUser().getUser());
        } catch (Exception e) {
            log.warn("编辑客户失败", e);
            return error(e.getMessage());
        }
        return success();
    }

    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteInnerCustomer/{ids}")
    public AjaxResult deleteInnerCustomer(@PathVariable Long[] ids) {
        try {
            restaurantCustomerService.deleteByIds(Arrays.asList(ids));
        } catch (Exception e) {
            log.warn("编辑客户失败", e);
            return error(e.getMessage());
        }
        return success();
    }

    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteNormalCustomer/{ids}")
    public AjaxResult deleteNormalCustomer(@PathVariable Long[] ids) {
        try {
            restaurantCustomerService.deleteByIds(Arrays.asList(ids));
        } catch (Exception e) {
            log.warn("编辑客户失败", e);
            return error(e.getMessage());
        }
        return success();
    }

    @Log(title = "删除客户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        int result = restaurantCustomerService.deleteByIds(Collections.singletonList(id));
        if (result == 1) {
            return success();
        }
        return error();
    }

    private void checkInnerAddParam(InnerCustomerAddDTO innerCustomerAddDTO) {
        if (innerCustomerAddDTO == null) {
            log.error("新增客户 参数为空");
            throw new ServiceException("新增客户 参数为空");
        }
    }

    private void checkNormalAddParam(NormalCustomerAddDTO normalCustomerAddDTO) {
        if (normalCustomerAddDTO == null) {
            log.error("新增客户 参数为空");
            throw new ServiceException("新增客户 参数为空");
        }
    }


    @Log(title = "用户信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerQueryDTO customer) {
        List<RestaurantCustomer> list = restaurantCustomerService.getNormalCustomer(customer);
        ExcelUtil<RestaurantCustomer> util = new ExcelUtil<>(RestaurantCustomer.class);
        util.exportExcel(response, list, "用户信息");
    }
}
